package com.daguchuangyi.erp_android.productlist.paramsfilter;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.constraint.ConstraintLayout;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.daguchuangyi.erp_android.R;
import com.daguchuangyi.erp_android.manager.ParameterManager;
import com.daguchuangyi.erp_android.model.product.Parameter;
import com.jude.utils.JUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.daguchuangyi.erp_android.manager.ParameterManager.TYPE_DATE;
import static com.daguchuangyi.erp_android.manager.ParameterManager.TYPE_NORMAL;
import static com.daguchuangyi.erp_android.manager.ParameterManager.TYPE_NUMBER;
import static com.daguchuangyi.erp_android.manager.ParameterManager.TYPE_SELECT;

/**
 * Created by lijianjian on 2018/3/10.
 */

public class ParamFilterSectionView extends ConstraintLayout {
    private static final String TAG = "ParamSectionView";

    private static final int TYPE_START_DATE = 0x42;
    private static final int TYPE_END_DATE = 0x43;

    //    private String mContentStr;
    //    private Set<String> mCheckOptionsSet;
    private ParameterManager.ParamCheckStatus mParamCheckStatus;
    private String mTitleStr;
    private int mMode;
//    private String mHintStr;

    private TextView mTitleTv;
    private EditText mEditText;
    private TextView mContentTv;
    private ImageView mArrowHintIv;
    private View mAreaWrapper;
    private EditText mLeftAreaEt;
    private EditText mRightAreaEt;
//    private OptionsPickerView mOptionsPickerView;

    private Parameter mParameter;
    private TimePickerView mStartTimePicker;
    private TimePickerView mEndTimePicker;

    public Parameter getParameter() {
        return mParameter;
    }

    public Map<Integer, ParameterManager.ParamCheckStatus> getCheckResult() {
        Map<Integer, ParameterManager.ParamCheckStatus> resultMap = new HashMap<>();
        if (mParameter != null) {
            resultMap.put(mParameter.getId(), mParamCheckStatus);
        }
        return resultMap;
    }

    public void bindParameter(Parameter parameter) {
        mParameter = parameter;
        mTitleStr = mParameter.getName();
        mParamCheckStatus = ParameterManager.getInstance().getParamsCheckStatus().get(mParameter.getId());
        if (mParamCheckStatus == null) {
            mParamCheckStatus = new ParameterManager.ParamCheckStatus();
        }
//        if (mParamCheckStatus != null && mParamCheckStatus.getType() == TYPE_SELECT) {
//            mContentStr = TextUtils.join("，", mParamCheckStatus.getOptionsCheck());
//        } else {
//            mParamCheckStatus = new ParameterManager.ParamCheckStatus();
//            mContentStr = "";
//        }
        String type = mParameter.getType();
        mEditText.setTag(parameter.getId());
        if (TextUtils.equals(type, "radio")) {
            mMode = TYPE_SELECT;
        } else if (TextUtils.equals(type, "date")) {
            mMode = TYPE_DATE;
        } else if (TextUtils.equals(type, "number")) {
            mMode = TYPE_NUMBER;
        } else {
            mMode = TYPE_NORMAL;
        }
        mParamCheckStatus.setType(mMode);
        refreshView();
    }

    public ParamFilterSectionView(Context context) {
        this(context, null);
    }

    public ParamFilterSectionView(Context context, AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public ParamFilterSectionView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        if (attrs != null) {
            TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ParamFilterSectionView);
            mTitleStr = ta.getString(R.styleable.ParamFilterSectionView_param_section_title);
            mMode = ta.getInt(R.styleable.ParamFilterSectionView_param_section_mode, 1);
//            mHintStr = ta.getString(R.styleable.ParamFilterSectionView_param_section_hint);
            ta.recycle();
        }

        init(context);
    }

    private void refreshView() {
        if (!mEditText.getTag().equals(mParameter.getId())) {
            JUtils.Log("Not current item so return.");
            return;
        }
        mTitleTv.setText(mTitleStr);
//        mEditText.setText(mContentStr, TextView.BufferType.EDITABLE);
        if (mMode == TYPE_NUMBER || mMode == TYPE_DATE) {
            mEditText.setVisibility(GONE);
            mArrowHintIv.setVisibility(GONE);
            mAreaWrapper.setVisibility(VISIBLE);
            if (mMode == TYPE_NUMBER) {
                mLeftAreaEt.setHint(mTitleStr + "数量");
                mRightAreaEt.setHint(mTitleStr + "数量");
                JUtils.Log(TAG, "set input type as number");
                mLeftAreaEt.setRawInputType(InputType.TYPE_CLASS_NUMBER);
                mLeftAreaEt.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
                if (mParamCheckStatus.getMin() != null) {
                    mLeftAreaEt.setText(String.valueOf(mParamCheckStatus.getMin()));
                }
                mLeftAreaEt.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int i1, int i2) {
                        if (start >= 0) {//从一输入就开始判断，
                            try {
                                long num = Long.parseLong(s.toString());
                                //判断当前edittext中的数字(可能一开始Edittext中有数字)是否大于max
                                if (num > Integer.MAX_VALUE) {
                                    s = String.valueOf(Integer.MAX_VALUE);//如果大于max，则内容为max
                                    mLeftAreaEt.setText(s);
//                                    Prompt.showTips(context, "金额不能超过" + max + "元");
                                    JUtils.ToastLong("数字过大，不能输入");

                                } else if (num < Integer.MIN_VALUE) {
                                    s = String.valueOf(Integer.MIN_VALUE);//如果小于min,则内容为min
                                    mLeftAreaEt.setText(s);
                                }
                            } catch (NumberFormatException e) {
                                JUtils.Log("ontextchanged", "==" + e.toString());
                            }
                        }
                    }

                    @Override
                    public void afterTextChanged(Editable editable) {
                        mParamCheckStatus.setMin(mLeftAreaEt.getText().toString());
                    }
                });

                mRightAreaEt.setRawInputType(InputType.TYPE_CLASS_NUMBER);
                mRightAreaEt.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
                if (mParamCheckStatus.getMax() != null) {
                    mRightAreaEt.setText(String.valueOf(mParamCheckStatus.getMax()));
                }
                mRightAreaEt.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        if (start >= 0) {//从一输入就开始判断，
                            try {
                                long num = Long.parseLong(s.toString());
                                //判断当前edittext中的数字(可能一开始Edittext中有数字)是否大于max
                                if (num > Integer.MAX_VALUE) {
                                    s = String.valueOf(Integer.MAX_VALUE);//如果大于max，则内容为max
                                    mRightAreaEt.setText(s);
//                                    Prompt.showTips(context, "金额不能超过" + max + "元");
                                    JUtils.ToastLong("数字过大，不能输入");

                                } else if (num < Integer.MIN_VALUE) {
                                    s = String.valueOf(Integer.MIN_VALUE);//如果小于min,则内容为min
                                    mRightAreaEt.setText(s);
                                }
                            } catch (NumberFormatException e) {
                                JUtils.Log("ontextchanged", "==" + e.toString());
                            }
                        }
                    }

                    @Override
                    public void afterTextChanged(Editable editable) {
                        mParamCheckStatus.setMax(mRightAreaEt.getText().toString());
                    }
                });
            } else {
                if (mMode == TYPE_DATE) {
                    mLeftAreaEt.setHint("开始日期");
                    mLeftAreaEt.setInputType(InputType.TYPE_NULL);
                    mLeftAreaEt.setOnClickListener(v -> {
                        Calendar startDate = Calendar.getInstance();
                        String minStr = mParamCheckStatus.getMin();
                        if (!TextUtils.isEmpty(minStr)) {
                            String[] dateStr = minStr.split("-");
                            int year = Integer.parseInt(dateStr[0]);
                            int month = Integer.parseInt(dateStr[1]) - 1;
                            int day = Integer.parseInt(dateStr[2]);
                            startDate.set(year, month, day);
                        }
                        showDatePickerDialog("开始日期", TYPE_START_DATE, startDate);
                    });
                    mLeftAreaEt.setOnFocusChangeListener((v, hasFocus) -> {
                        if (hasFocus) {
                            Calendar startDate = Calendar.getInstance();
                            String minStr = mParamCheckStatus.getMin();
                            if (!TextUtils.isEmpty(minStr)) {
                                String[] dateStr = minStr.split("-");
                                int year = Integer.parseInt(dateStr[0]);
                                int month = Integer.parseInt(dateStr[1]) - 1;
                                int day = Integer.parseInt(dateStr[2]);
                                startDate.set(year, month, day);
                            }
                            showDatePickerDialog("开始日期", TYPE_START_DATE, startDate);
                        }
                    });
                    mLeftAreaEt.setText(mParamCheckStatus.getMin());

                    mRightAreaEt.setHint("结束日期");
                    mRightAreaEt.setInputType(InputType.TYPE_NULL);
                    mRightAreaEt.setOnClickListener(v -> {
                        Calendar endDate = Calendar.getInstance();
                        String maxStr = mParamCheckStatus.getMax();
                        if (!TextUtils.isEmpty(maxStr)) {
                            String[] dateStr = maxStr.split("-");
                            int year = Integer.parseInt(dateStr[0]);
                            int month = Integer.parseInt(dateStr[1]) - 1;
                            int day = Integer.parseInt(dateStr[2]);
                            endDate.set(year, month, day);
                        }
                        showDatePickerDialog("结束日期", TYPE_END_DATE, endDate);
                    });
                    mRightAreaEt.setOnFocusChangeListener((v, hasFocus) -> {
                        if (hasFocus) {
                            Calendar endDate = Calendar.getInstance();
                            String maxStr = mParamCheckStatus.getMax();
                            if (!TextUtils.isEmpty(maxStr)) {
                                String[] dateStr = maxStr.split("-");
                                int year = Integer.parseInt(dateStr[0]);
                                int month = Integer.parseInt(dateStr[1]) - 1;
                                int day = Integer.parseInt(dateStr[2]);
                                endDate.set(year, month, day);
                            }
                            showDatePickerDialog("结束日期", TYPE_END_DATE, endDate);
                        }
                    });
                    mRightAreaEt.setText(mParamCheckStatus.getMax());
                }
            }

        } else {
            mAreaWrapper.setVisibility(GONE);
            if (mMode == TYPE_SELECT) {
                // in select mode
                mEditText.setVisibility(GONE);
                mContentTv.setVisibility(VISIBLE);
                String contentStr = "";
                if (mParamCheckStatus.getOptionsCheck() != null) {
                    contentStr = TextUtils.join("，", mParamCheckStatus.getOptionsCheck());
                }
                mContentTv.setText(contentStr);
                mArrowHintIv.setVisibility(VISIBLE);
                mContentTv.setHint("请选择" + mTitleStr);

                List<String> typeList = mParameter.getOptionValue();
                setOnClickListener(v -> {
                    JUtils.closeInputMethod((Activity) getContext());
                    MultiPickerView pickerView = new MultiPickerView.Builder(getContext(), optionsCheck -> {
                        mParamCheckStatus.setOptionsCheck(optionsCheck);
                        String selectResult = TextUtils.join("，", optionsCheck);
                        mContentTv.setText(selectResult);
                    }).setTitle(mTitleStr).setContent(typeList, mParamCheckStatus.getOptionsCheck()).build();
                    pickerView.show();
                });
            } else {
                mContentTv.setVisibility(GONE);
                mEditText.setVisibility(VISIBLE);
                mArrowHintIv.setVisibility(GONE);
//                if (mMode == TYPE_NUMBER) {
//                    JUtils.Log(TAG, "set input type as number");
//                    mEditText.setRawInputType(InputType.TYPE_CLASS_NUMBER);
//                    mEditText.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
//                } else if (mMode == TYPE_NORMAL) {
                JUtils.Log(TAG, "set input type as normal");
                mEditText.setRawInputType(InputType.TYPE_CLASS_TEXT);
//                }
                mEditText.setHint("请输入" + mTitleStr);
                String selectResult = "";
                if (mParamCheckStatus.getOptionsCheck() != null) {
                    selectResult = TextUtils.join("，", mParamCheckStatus.getOptionsCheck());
                }

                mEditText.setText(selectResult);
                mEditText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void afterTextChanged(Editable editable) {
//                        mCheckOptionsSet.clear();
                        String contentStr = mEditText.getText().toString().trim();
                        Set<String> contentSet = new HashSet<>();
                        contentSet.add(contentStr);
                        mParamCheckStatus.setOptionsCheck(contentSet);
                    }
                });
            }
        }
    }

    private void showDatePickerDialog(String title, int type, Calendar currentDate) {
        JUtils.closeInputMethod((Activity) getContext());
        mStartTimePicker = new TimePickerView.Builder(getContext(), (date, v) -> {
            SimpleDateFormat format0 = new SimpleDateFormat("yyyy-MM-dd");
            String time = format0.format(date.getTime());//这个就是把时间戳经过处理得到期望格式的时间
            if (type == TYPE_START_DATE) {
                mParamCheckStatus.setMin(time);
                mLeftAreaEt.setText(time);
            } else if (type == TYPE_END_DATE) {
                mRightAreaEt.setText(time);
                mParamCheckStatus.setMax(time);
            }
        }).setLayoutRes(R.layout.dialog_date_picker, v -> {
            final TextView tvSubmit = v.findViewById(R.id.i_confirm_tv);
            final TextView tvCancel = v.findViewById(R.id.i_reset_tv);
            final TextView tvTitle = v.findViewById(R.id.title_tv);
            tvTitle.setText(title);
            tvSubmit.setOnClickListener(v12 -> {
                mStartTimePicker.returnData();
                mStartTimePicker.dismiss();
            });
            tvCancel.setOnClickListener(v1 -> {
                if (type == TYPE_START_DATE) {
                    mParamCheckStatus.setMin(null);
                    mLeftAreaEt.setText("");
                } else if (type == TYPE_END_DATE) {
                    mRightAreaEt.setText("");
                    mParamCheckStatus.setMax(null);
                }
                mStartTimePicker.dismiss();
            });
        })
                .setDate(currentDate)
                .setType(new boolean[]{true, true, true, false, false, false}).build();
        mStartTimePicker.show();
    }

    private void init(Context context) {
        inflate(context, R.layout.view_params_section_item_layout, this);
        mTitleTv = findViewById(R.id.title_tv);
        mEditText = findViewById(R.id.content_et);
        mContentTv = findViewById(R.id.content_tv);
        mArrowHintIv = findViewById(R.id.arrow_hint_iv);
        mAreaWrapper = findViewById(R.id.area_input_wrapper);
        mLeftAreaEt = findViewById(R.id.start_area_et);
        mRightAreaEt = findViewById(R.id.end_area_et);
    }
}
